import { useState, type FC } from 'react';

import { type AccessProtocol } from '@/api/equipmentAccessProtocolApi';
import {
  equipmentProductListApi,
  equipmentProductSaveOrUpdateApi,
} from '@/api/equipmentProductApi';
import { ProductNodeType, getEnumLabel } from '@/constants';
import EquipmentProductAddForm from '@/pages/Equipment/Product/modules/add';

/**
 * 接入协议添加表单组件属性
 */
interface AccessProtocolAddProps {
  /** 表单实例 */
  form: FormInstance;
  /** 协议数据 */
  data: AccessProtocol;
}

/**
 * 泛协议接入实例添加/编辑表单
 */
const AccessProtocolAddForm: FC<AccessProtocolAddProps> = props => {
  const { form } = props;
  const [addInfo, setAddInfo] = useState(1);

  // 产品添加抽屉相关状态
  const [productDrawerShow, setProductDrawerShow] = useState(false);
  const [productForm] = AForm.useForm();
  const [productSubmitLoading, setProductSubmitLoading] = useState(false);

  /**
   * 获取产品列表
   */
  const fetchRemoteSelectData = async (params: FetchParams) => {
    const res = await equipmentProductListApi({
      ...params,
    });
    if (res.success) {
      const { page, pageSize } = params;
      const hasMore = page * pageSize < res.data.total;
      const newData = res.data.records
        .filter(item => item.accessProtocolName == '泛连接')
        .map(item => {
          return {
            ...item,
            label: `${item.productName}(${getEnumLabel(ProductNodeType, item.nodeType || 1)})`,
            value: item.code,
          };
        });
      return {
        data: newData,
        total: res.data.total,
        hasMore,
      };
    }
    return {
      data: [],
      total: 0,
      hasMore: false,
    };
  };

  // 处理产品添加
  const handleProductSubmit = async () => {
    try {
      setProductSubmitLoading(true);
      const values = await productForm.validateFields();

      // 处理城市数据
      const cityData = values.cityValue || {};
      const submitData = {
        ...values,
        provinceName: cityData.province,
        cityName: cityData.city,
        source: 0, // 默认来源
      };

      const res = await equipmentProductSaveOrUpdateApi(submitData);
      if (res.success) {
        window.$message.success('产品添加成功');
        productForm.resetFields();
        setProductDrawerShow(false);
        setAddInfo(addInfo + 1);
        // 刷新产品列表 - 这里可以触发RemoteSelect的刷新
      } else {
        window.$message.error(res.message || '产品添加失败');
      }
    } catch (error) {
      console.error('产品添加失败:', error);
      window.$message.error('产品添加失败，请重试');
    } finally {
      setProductSubmitLoading(false);
    }
  };

  return (
    <>
      <ARow gutter={16}>
        <ACol span={24}>
          <AForm.Item
            name="name"
            label="实例名称"
            rules={[{ required: true, message: '请输入实例名称' }]}
          >
            <AInput placeholder="请输入实例名称" allowClear />
          </AForm.Item>
        </ACol>

        <ACol span={20}>
          <AForm.Item
            name="productCode"
            label="选择产品"
            rules={[{ required: true, message: '请选择产品类型' }]}
          >
            <RemoteSelect
              searchParams={{
                addInfo,
              }}
              onSelect={(_e, options) => {
                form.setFieldValue('enterpriseName', options.label);
              }}
              fetchData={fetchRemoteSelectData}
            />
          </AForm.Item>
        </ACol>
        <ACol span={4} className="flex-center relative top-1">
          <AButton
            type="primary"
            onClick={() => {
              productForm.resetFields();
              setProductDrawerShow(true);
            }}
          >
            添加产品
          </AButton>
        </ACol>
        <ACol span={24}>
          <AForm.Item
            name="remark"
            label="实例描述"
            rules={[{ max: 200, message: '实例描述不能超过200个字符' }]}
          >
            <AInput.TextArea
              placeholder="请输入实例描述"
              rows={4}
              allowClear
              showCount
              maxLength={200}
            />
          </AForm.Item>
        </ACol>
      </ARow>

      {/* 产品添加抽屉 */}
      <ADrawer
        title="新增产品"
        width={600}
        onClose={() => setProductDrawerShow(false)}
        open={productDrawerShow}
        footer={
          <div className="flex justify-end space-x-2">
            <AButton onClick={() => setProductDrawerShow(false)} disabled={productSubmitLoading}>
              取消
            </AButton>
            <AButton type="primary" onClick={handleProductSubmit} loading={productSubmitLoading}>
              确定
            </AButton>
          </div>
        }
      >
        <div className="w-full px-4 py-4">
          <AForm form={productForm} layout="vertical" labelAlign="right" labelCol={{ span: 24 }}>
            <EquipmentProductAddForm form={productForm} data={{}} fromProtocol={true} />
          </AForm>
        </div>
      </ADrawer>
    </>
  );
};

export default AccessProtocolAddForm;
